package com.ruoyi.pointRecord.service.impl;

import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrackMap;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.response.QueryTrackMapResp;
import com.kuaidi100.sdk.utils.SignUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pointRecord.domain.PointsExchangeRecord;
import com.ruoyi.pointRecord.service.ILogisticsQueryService;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class LogisticsQueryServiceImpl implements ILogisticsQueryService {

    @Value("${spring.kuaidi100.key}")
    private String key;

    @Value("${spring.kuaidi100.customer}")
    private String customer;

    @Value("${spring.kuaidi100.base-url}")
    private String baseUrl;

    // 物流公司编码映射
    private static final Map<String, String> COMPANY_MAP = Map.of(
            "顺丰速运", "shunfeng",
            "中通快递", "zhongtong",
            "圆通速递", "yuantong",
            "申通快递", "shentong",
            "韵达速递", "yunda",
            "百世快递", "huitongkuaidi",
            "京东快递", "jd",
            "邮政快递", "ems"
    );

    /**
     * 查询物流信息
     */
    public Map<String, Object> queryLogistics(String trackingNumber, String logisticsCompany) {
        return queryLogistics(trackingNumber, logisticsCompany, null, null, null);
    }

    /**
     * 查询物流信息，支持手机号和地址信息
     */
    public Map<String, Object> queryLogistics(String trackingNumber, String logisticsCompany,
                                              String phone, String fromAddress, String toAddress) {
        try {
            // 获取物流公司编码
            String companyCode = COMPANY_MAP.getOrDefault(logisticsCompany, logisticsCompany.toLowerCase());

            // 创建查询请求对象
            QueryTrackReq queryTrackReq = new QueryTrackReq();
            QueryTrackParam queryTrackParam = new QueryTrackParam();

            // 设置基本参数
            queryTrackParam.setCom(companyCode);
            queryTrackParam.setNum(trackingNumber);
            queryTrackParam.setResultv2("2"); // 返回详细信息

            // 设置可选参数
            if (StringUtils.isNotBlank(phone)) {
                queryTrackParam.setPhone(phone);
            }
            if (StringUtils.isNotBlank(fromAddress)) {
                queryTrackParam.setFrom(fromAddress);
            }
            if (StringUtils.isNotBlank(toAddress)) {
                queryTrackParam.setTo(toAddress);
            }

            // 转换为JSON字符串
            String param = new Gson().toJson(queryTrackParam);

            // 设置请求参数
            queryTrackReq.setParam(param);
            queryTrackReq.setCustomer(customer);
            queryTrackReq.setSign(SignUtils.querySign(param, key, customer));

            // 执行查询
            IBaseClient baseClient = new QueryTrackMap();
            HttpResult result = baseClient.execute(queryTrackReq);

            // 解析返回结果
            QueryTrackMapResp queryTrackMapResp = new Gson().fromJson(result.getBody(), QueryTrackMapResp.class);

            // 转换为Map格式返回（保持与原接口兼容）
            Map<String, Object> response = new HashMap<>();
            if (queryTrackMapResp != null) {
                response.put("message", queryTrackMapResp.getMessage());
                response.put("state", queryTrackMapResp.getState());
                response.put("status", queryTrackMapResp.getStatus());
                response.put("condition", queryTrackMapResp.getCondition());
                response.put("ischeck", queryTrackMapResp.getIscheck());
                response.put("com", queryTrackMapResp.getCom());
                response.put("nu", queryTrackMapResp.getNu());
                response.put("data", queryTrackMapResp.getData());

                log.info("物流查询成功，单号：{}，状态：{}", trackingNumber, queryTrackMapResp.getState());
            }

            return response;

        } catch (Exception e) {
            log.error("物流查询异常，单号：{}，异常信息：{}", trackingNumber, e.getMessage());
            throw new RuntimeException("物流查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据PointsExchangeRecord查询物流
     */
    public Map<String, Object> queryLogistics(PointsExchangeRecord pointsExchangeRecord) {
        return queryLogistics(
                pointsExchangeRecord.getTrackingNumber(),
                pointsExchangeRecord.getLogisticsCompany(),
                pointsExchangeRecord.getContactPhone(),
                "广东省湛江市",
                pointsExchangeRecord.getDeliveryAddress()
        );
    }

}

